<?php
namespace Asset\Controller;
use Common\Controller\AdminbaseController;
class BalanceController extends AdminbaseController {
	protected $user_wallet_model;

	function _initialize() {
		parent::_initialize();
		$this->user_wallet_model = D("UserWallet");
		$this->real_users_model = D("RealUsers");
        $this->backup_path = '/data/';
        $this->gender = array(
            array(id => 0, name=>'保密'),
            array(id => 1, name=>'男'),
            array(id => 2, name=>'女'),
        );
	}
	function index(){
		$this->_lists();
		$this->display();
	}
	function _lists(){
		if(I('param.')){
            if(I('param.keyword')){
                    $search[] = array('money'=>array('egt',I('param.keyword')));
            }
			$_GET['keyword']=I('param.keyword');
		}
		$count=$this->user_wallet_model->where($search)->count();
		$page = $this->page($count, 50);
		$uwallets=$this->user_wallet_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("money DESC,real_user_id DESC")->select();
		if($uwallets){
			$ids = NULL;
			foreach($uwallets as $uwallet){
				$ids[] = $uwallet['real_user_id'];
			}
			$rusers = $this->real_users_model->where(array('id'=>array('in',$ids)))->select();
			$this->assign("rusers", $rusers);
		}
    	$this->assign('page', $page->show('Admin'));
		$this->assign("uwallets", $uwallets);
		$this->assign("count", $count);
	}
	function edit(){
		$id = intval(I("get.id"));
		$this->assign('gender', $this->gender);
		$uwallet = $this->user_wallet_model->where(array('real_user_id'=>$id))->find();
		$ruser = $this->real_users_model->where(array('id'=>$id))->find();
		$this->assign("uwallet", $uwallet);
		$this->assign("ruser", $ruser);
		$this->display();
	}

    public function download(){
        $backup_name = isset($_GET['backup']) && trim($_GET['backup']) ? trim($_GET['backup']) :
            $this->error('请选择文件名称！');
        $file = isset($_GET['file']) && trim($_GET['file']) ? trim($_GET['file']) : $this->
            error('请选择文件文件！');
        $sql_file = SITE_PATH . $this->backup_path . $backup_name . '/' . $file;
        if (file_exists($sql_file)){
            header('Content-type: application/unknown');
            header('Content-Disposition: attachment; filename="' . $file . '"');
            header("Content-Length: " . filesize($sql_file) . "; ");
            readfile($sql_file);
        }else{
            $this->error('文件不存在！');
        }
    }
	public function export_csv($filename, $data){
		$file_hwnd=fopen('data/runtime/'.$filename,"w");
		header("Content-type:text/csv");
		header("Content-Disposition:attachment;filename=".$filename);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		fwrite($file_hwnd,$data);
		fclose($file_hwnd);
	}
	function amountcsv(){
		if(I('param.')){
            if(I('param.keyword')){
                    $search[] = array('money'=>array('egt',I('param.keyword')));
            }
		}
		if(empty($search)){
			$search[] = array('money'=>array('egt',1));
		}
		$uwallets=$this->user_wallet_model->where($search)
		->order("money DESC,real_user_id DESC")->select();
		if($uwallets){
			$ids = NULL;
			foreach($uwallets as $uwallet){
				$ids[] = $uwallet['real_user_id'];
			}
			$rusers = $this->real_users_model->where(array('id'=>array('in',$ids)))->select();
		}

		if(count($rusers) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$head[] = iconv('utf-8','GBK',",openid,用户昵称,姓名,注册日期,最后登录日期,电话,地址,账户余额(元)\r\n");
		if($rusers){
			set_time_limit(0);
			foreach($rusers as$ruser){
				$nickname = str_replace(array("\r\n", "\r", "\n",",","."), "", $ruser['nickname']);
				$moneys = 0;
				foreach($uwallets as $uwallet){
					if($uwallet['real_user_id'] == $ruser['id']){
						$moneys =$uwallet['money'];
					}
				}
				$content[] = iconv('utf-8','GBK',$ruser['weixin_id']).",".
						iconv('utf-8','GBK',$nickname).",".
						iconv('utf-8','GBK',$ruser['realname']).",".
						iconv('utf-8','GBK',$ruser['created_at']).",".
						iconv('utf-8','GBK',$ruser['last_login']).",".
						iconv('utf-8','GBK',$ruser['phone']).",".
						iconv('utf-8','GBK',$ruser['address']).",".
						iconv('utf-8','GBK',$moneys/100).","."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Balance/download', array('backup'=>'runtime', 'file'=>"$csvname")));
	}
}
